package api

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"runtime"
	"strconv"
	"time"
)

type SystemApi struct {
}

func NewSystemApi(c *gin.Context) SystemApi {
	a := SystemApi{}
	return a
}

func (api SystemApi) ReqId(c *gin.Context) {
	reqId, _ := c.Get("reqId")
	c.JSON(http.StatusOK, gin.H{
		"message": "success",
		"reqId":   reqId.(string),
	})
}
func (api SystemApi) CtxEnd(c *gin.Context) {
	ctx := c.Request.Context()
	go func(ctx context.Context) {
		time.Sleep(2 * time.Second)
		select {
		case <-ctx.Done():
		default:
		}
	}(ctx)
	c.JSON(http.StatusOK, gin.H{
		"message": "success",
		"reqId":   "ctxEnd",
	})
}
func (api SystemApi) Ping(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "pong",
		"lang":    "GO语言",
	})
}

func (api SystemApi) Hostname(c *gin.Context) {
	hostname, err := os.Hostname()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"hostname": "没有获取到hostname",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"hostname":     hostname,
		"numGoroutine": runtime.NumGoroutine(),
	})
}

func (api SystemApi) Num(c *gin.Context) {
	feeStr := c.DefaultQuery("fee", "")
	fee, _ := strconv.Atoi(feeStr)

	priceStr := c.DefaultQuery("price", "")
	price, _ := strconv.ParseFloat(priceStr, 32)
	c.JSON(http.StatusOK, gin.H{
		"fee":   fee,
		"price": price,
	})
}

func (api SystemApi) DataExample(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"code":    "0",
		"message": "pong",
		"data": map[string]string{
			"id":   "2",
			"name": "bb",
		},
	})
}
